import { createSlice } from '@reduxjs/toolkit';

// 创建音频管理slice
const audioSlice = createSlice({
  name: 'audio',
  initialState: {
    uploadedAudios: {}, // 存储上传的音频 {menuKey_uploadKey: audioInfo}
    currentAudio: null   // 当前使用的单音频
  },
  reducers: {
    setUploadedAudio: (state, action) => {
      const { key, audioInfo } = action.payload;
      if (state.uploadedAudios[key]) {
        // 如果已存在该键，则添加到现有数组中
        state.uploadedAudios[key] = [...state.uploadedAudios[key], audioInfo];
      } else {
        // 否则创建新数组
        state.uploadedAudios[key] = [audioInfo];
      }
      // 如果是单音频上传，同时更新currentAudio
      if (key.includes('single') || key.includes('main') || key.includes('reference')) {
        state.currentAudio = audioInfo;
      }
    },
    setCurrentAudio: (state, action) => {
      state.currentAudio = action.payload;
    },
    clearAudios: (state) => {
      state.uploadedAudios = {};
      state.currentAudio = null;
    },
    removeAudio: (state, action) => {
      const key = action.payload;
      const audioToRemove = state.uploadedAudios[key];
      delete state.uploadedAudios[key];
      if (state.currentAudio === audioToRemove) {
        state.currentAudio = null;
      }
    }
  }
});

// 导出actions
export const { setUploadedAudio, setCurrentAudio, clearAudios, removeAudio } = audioSlice.actions;

// 导出reducer
export default audioSlice.reducer;

// 导出选择器
export const selectAudio = (state) => state.audio;
export const selectCurrentAudio = (state) => state.audio.currentAudio;
export const selectUploadedAudios = (state) => state.audio.uploadedAudios;